package cn.relx.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
        String token = currentContext.getRequest().getHeader("token");
        HashMap<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                map.put("success",false);
                map.put("message","服务器异常!");
                map.put("noLogin","请登录!");
                String toJSONString = JSONObject.toJSONString(map);
                writer.write(toJSONString);
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        return null;
    }
}
